/*
 * MIT License
 *
 * Copyright (c) 2024 恩爸编程
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.enba.boot.msg.strategy;

import com.enba.boot.msg.properties.MsgProperties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeChatWorkMessagePushStrategy implements MessagePushStrategy {

  private final Logger logger = LoggerFactory.getLogger("enba-boot-root");

  private final MsgProperties msgProperties;

  public WeChatWorkMessagePushStrategy(MsgProperties msgProperties) {
    this.msgProperties = msgProperties;
  }

  @Override
  public void pushMessage(String message) {
    try {
      URL url = new URL(msgProperties.getWeChatWorkWebhookUrl());
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

      String data = "{\"msgtype\": \"text\", \"text\": {\"content\": \"" + message + "\"}}";
      connection.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line;
      StringBuilder response = new StringBuilder();
      while ((line = reader.readLine()) != null) {
        response.append(line);
      }
      reader.close();
      connection.disconnect();

      logger.info("企业微信消息推送结果: {}", response);
    } catch (IOException e) {
      logger.error("钉钉消息推送失败: {}", e.getMessage(), e);
    }
  }

  @Override
  public <R> R pushMessage(String message, Function<String, R> function) {
    try {
      URL url = new URL(msgProperties.getWeChatWorkWebhookUrl());
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

      String data = "{\"msgtype\": \"text\", \"text\": {\"content\": \"" + message + "\"}}";
      connection.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line;
      StringBuilder response = new StringBuilder();
      while ((line = reader.readLine()) != null) {
        response.append(line);
      }
      reader.close();
      connection.disconnect();

      logger.info("企业微信消息推送结果: {}", response);
      return function.apply(response.toString());
    } catch (IOException e) {
      logger.error("企业微信消息推送失败: {}", e.getMessage(), e);
      return function.apply("企业微信消息推送失败:" + e.getMessage());
    }
  }
}
